<?php

namespace App\Http\Api\Services;

use App\Exceptions\InvalidRequestException;
use App\Http\Services\BaseService;

class FxgService extends BaseService
{

    public function sendFxgRequest($attributes)
    {
        //放心购Api
        $timestamp = $attributes['timestamp'];
        $APP_KEY    =   $attributes['APP_KEY'];
        $APP_SECRET =   $attributes['APP_SECRET'];
        $access_token =   $attributes['access_token'];
        $param_arr  =   $attributes['param_arr'] ?? '';

        $host = "https://openapi-fxg.jinritemai.com";
        $c = $attributes['c'];
        $a = $attributes['a'];
        $method = $c.".".$a;

        // 参数按key值排序
        if(!empty($attributes['param_json'])){
            $param_json = $attributes['param_json'];
        }else{
            ksort($param_arr);
            $param_json = json_encode($param_arr);
        }


        // 构造请求url
        $base_url = $host . '/' . $c . '/' . $a . '?';
        // 计算签名
        $str = "app_key" . $APP_KEY . "method" . $method . "param_json" . $param_json . "timestamp" . $timestamp . "v" . "2";
        $md5_str = $APP_SECRET . $str . $APP_SECRET;
        $sign = md5($md5_str);

        //请求参数
        $request_data = [
            'app_key' => $APP_KEY,
            "access_token"=>$access_token,
            'method' => $method,
            'param_json' => $param_json,
            'timestamp' => $timestamp,
            'v' => "2",
            'sign' => $sign,
        ];

        $res = $this->send_post($base_url, $request_data);
        dd($res);
		$res = str_replace('{"err_no":30008,"message":"app_key已过期失效，请前往抖店开放平台进行升级。升级指南：https://op.jinritemai.com/docs/guide-docs/6/31"}',"",$res);

        $data = json_decode($res, true)  ?? [];
		
        return $data;

    }
    //url请求
    public function send_post($url, $post_data)
    {
        $postdata = http_build_query($post_data);
        $options = array(
            'http' => array(
                'method' => 'POST',
                'header' => 'Content-type:application/x-www-form-urlencoded',
                'content' => $postdata,
                'timeout' => 15 * 60 // 超时时间（单位:s）
            )
        );
        $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        return $result;
    }


    //上传商品规格信息
    public function addGoodsSpec($data){
        $APP_KEY        =   $data['app_key'] ?? '3356345407633543075';
        $APP_SECRET     =   $data['app_secret'] ?? '1147f03780a21832c72fc608952c2bec';
        $name           =   $data['spec_name'] ?? '规格名称';
        /*处理specs*/
        $skus_data      =   $data['skus'];
        $color          =   '颜色|';
        $size           =   '尺码|';
        $color_arr      =   [];
        $size_arr       =   [];
        foreach ($skus_data as $k=>$v){
            array_push($color_arr,$v['sku_color']);
            array_push($size_arr,$v['sku_size']);

        }
        $color_arr      =   array_unique($color_arr);
        $size_arr       =   array_unique($size_arr);
        $color          .=   implode(",",$color_arr);
        $size           .=   implode(",",$size_arr);
        $specs          =   $color.'^'.$size;//'颜色|黑色,白色^尺码|S,M,L'
        /*上传JSON*/
        $param_json     =   '{"name":"'.$name.'","specs":"'.$specs.'"}';
        $attributes['APP_KEY']      =   $APP_KEY;
        $attributes['APP_SECRET']   =   $APP_SECRET;
        $attributes['timestamp']    =   date('Y-m-d H:i:s', time());
        $attributes['c']            =   'spec';
        $attributes['a']            =   'add';
        $attributes['param_json']   =   $param_json;


        $spec_data =   $this->sendFxgRequest($attributes);//上传

        return $spec_data;
    }


    /*添加商品*/
    public function addGoods($data){
        $goods_data =   '';
        $attributes = [];
        if(!empty($data['spec_id'])){

            $attributes['APP_KEY']      =   $data['app_key'];
            $attributes['APP_SECRET']   =   $data['app_secret'];
            $attributes['timestamp']    =   date('Y-m-d H:i:s', time());
            $attributes['c']            =   'product';
            $attributes['a']            =   'add';
            $attributes['param_json']   =   $data['param_json'];

            $goods_data =   $this->sendFxgRequest($attributes);
        }


        return $goods_data;
    }

    /*编辑商品*/
    public function editGoods($data){

        $attributes['APP_KEY']      =   $data['app_key'];
        $attributes['APP_SECRET']   =   $data['app_secret'];
        $attributes['timestamp']    =   date('Y-m-d H:i:s', time());
        $attributes['c']            =   'product';
        $attributes['a']            =   'edit';
        $attributes['param_json']   =   $data['param_json'];

        $goods_data =   $this->sendFxgRequest($attributes);

        return $goods_data;

    }


    /*上传sku信息*/
    public function addGoodsSkus($data){

        $product_id         =   $data['out_product_id'];
        $price              =   '';
        $detail_id          =   '';
        $spec_detail_ids    =   '';
        $stock_num          =   '';
        $index              =   0;
        $specId             =   '';
        $settlement_price   =   '';
        $code               =   '';
        foreach ($data['skus']  as   $k=>$v){
            $detail_id      .=      $k;
            $price          .=      $v['price'];
            $spec_detail_ids.=      $v['spec_detail_ids'];
            $stock_num      .=      $v['stock'];
            $specId         .=      $data['spec_id'];
            $settlement_price   .=  '0';
            $code           .=      $v['code'];
            if($index+1 < count($data['skus'])){
                $detail_id      .=      '|';
                $price          .=      '|';
                $spec_detail_ids.=      '^';

                $stock_num      .=      '|';
                $specId         .=      '|';
                $settlement_price   .=  '|';
                $code           .=      '|';
            }
            $index++;
        }
        if($data['type'] == 2){
            $param_json =   '{"code":"'.$code.'","out_sku_id":"'.$detail_id.'","price":"'.$price.'","product_id":"'.$product_id.'","settlement_price":"'.$settlement_price.'","spec_detail_ids":"'.$spec_detail_ids.'","spec_id":"'.$specId.'","stock_num":"'.$stock_num.'"}';
        }else{
            $param_json =   '{"code":"'.$code.'","out_product_id":"'.$product_id.'","out_sku_id":"'.$detail_id.'","price":"'.$price.'","settlement_price":"'.$settlement_price.'","spec_detail_ids":"'.$spec_detail_ids.'","spec_id":"'.$specId.'","stock_num":"'.$stock_num.'"}';
        }





            $APP_KEY    =   $data['app_key'] ?? '3356345407633543075';
            $APP_SECRET =   $data['app_secret'] ?? '1147f03780a21832c72fc608952c2bec';

            $attributes['APP_KEY']      =   $APP_KEY;
            $attributes['APP_SECRET']   =   $APP_SECRET;
            $attributes['timestamp']    =   date('Y-m-d H:i:s', time());
            $attributes['c']            =   'sku';
            $attributes['a']            =   'addAll';
            $attributes['param_json']   =   $param_json;


            $sku_data =   $this->sendFxgRequest($attributes);

        return $sku_data;
    }





}